﻿using Shop.Model.Advert;
using Shop.Model.DB;
using Shop.RemoteModel;
using Shop.RemoteModel.Advert.Model;
using Shop.Repository;
using SqlSugar;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Shop.Collect.lmpl
{
    internal class AdvertCollect : IAdvertCollect
    {
        private readonly IAdvertRepository _Repository;

        public AdvertCollect (IAdvertRepository repository)
        {
            this._Repository = repository;
        }
        public bool CheckIsNull (long placeId)
        {
            return this._Repository.IsExist(c => c.PlaceId == placeId) == false;
        }

        public Dictionary<long, int> GetAdvertNum (long[] placeId)
        {
            return this._Repository.GroupBy(c => placeId.Contains(c.PlaceId), c => c.PlaceId, c => new
            {
                c.PlaceId,
                num = SqlFunc.AggregateCount(c.PlaceId)
            }).ToDictionary(c => c.PlaceId, c => c.num);
        }
        public void Delete (DBAdvert advert)
        {
            if (advert.AdvertStatus != AdvertStatus.起草)
            {
                throw new ErrorException("shop.advert.no.allow.delete");
            }
            this._Repository.Delete(advert.Id);
        }
        public long Add (AdvertAddArg add)
        {
            return this._Repository.Add(add);
        }
        public Result[] Query<Result> (AdvertQueryParam query, IBasicPage paging, out int count) where Result : class
        {
            return this._Repository.Query<Result>(query, paging, out count);
        }
        public DBAdvert Get (long id)
        {
            return this._Repository.Get(id);
        }
        public void Enable (DBAdvert advert)
        {
            if (advert.AdvertStatus == AdvertStatus.启用)
            {
                return;
            }
            else if (this._Repository.IsExist(c => c.PlaceId == advert.PlaceId &&
            c.RelationId == advert.RelationId &&
            c.RelationType == advert.RelationType &&
            c.AdvertStatus == AdvertStatus.启用))
            {
                throw new ErrorException("shop.advert.repeat");
            }
            this._Repository.Enable(advert);
        }
        public void Stop (DBAdvert advert)
        {
            if (advert.AdvertStatus == AdvertStatus.停用)
            {
                return;
            }
            this._Repository.Stop(advert);
        }
        public void End (DBAdvert advert)
        {
            if (advert.AdvertStatus == AdvertStatus.结束)
            {
                return;
            }
            this._Repository.End(advert);
        }
        public bool Set (DBAdvert advert, AdvertSetArg arg)
        {
            if (advert.AdvertStatus != AdvertStatus.起草 && advert.AdvertStatus != AdvertStatus.停用)
            {
                throw new ErrorException("shop.advert.not.allow.update");
            }
            return this._Repository.Update(advert, arg);
        }
    }
}
